var mongoose = require("mongoose"); //  顶会议用户组件

var db = require("./db.js");

var MD5 = require("crypto-js/md5");

var autoIncrement = require('mongoose-auto-increment');   //自增ID 模块

var Schema = db.Schema; //  创建模型

autoIncrement.initialize(db);   //初始化
var userSchema = new Schema({
    username: String,
    password: String,
    name: String,
    place: String,
    token: String,
    last_time: {type: Date, default: Date.now}
}); //  定义了一个新的模型，但是此模式还未和user集合有关联
userSchema.plugin(autoIncrement.plugin, {
    model: 'user',   //数据模块，需要跟同名 x.model("Books", infoSchema);
    field: 'id',     //字段名
});
// userSchema.pre('update', function(next) {
//   console.log("pre processing");
//   this.last_time = Date.now();
//   next();
// });

var userModel = db.model('user', userSchema);

var UserController = {};

UserController.signup = function(usr, pwd, name, place, callback){
  if(!usr || !pwd || !name || !place){
    callback(203);
    return;
  }
  var encryptPwd = MD5(pwd + "").toString().toUpperCase();
  var data = {username : usr, password: encryptPwd, name: name, place: place};
  userModel.findOne({username: usr},function(error, result){
    if(error){
      callback(201);
      return;
    }else{
      if(result){
        callback(205);
        return;
      }else{
        var entity = new userModel(data);
        entity.save(function(error) {
          if(error){
            callback(201);
          }else{
            callback(200);
          }
        });
      }
    }
  });
}
UserController.login = function(usr, pwd, callback){
  if(!usr || !pwd){
    callback(203);
    return;
  }
  var encryptPwd = MD5(pwd + "").toString().toUpperCase();
  var criteria = {username: usr, password: encryptPwd}; // 查询条件
  userModel.findOne(criteria, function(error, result){
      if(error) {
          console.log(error);
          callback(201);
      } else {
        if(result){
          var token = MD5(Date.now().toString(32) + result.id).toString().toUpperCase();
          var conditions = {id: result.id};
          var update     = {$set : {token : token, last_time: Date.now()}};
          userModel.update(conditions, update, function(error){
              if(error) {
                  callback(201);
                  return;
              } else {
                result.token = token;
                callback(200 ,result);
              }
          });
        }else{
            callback(204);
        }
      }
  });
}
UserController.logout = function(token, callback){
  if(!token){
    callback(203);
    return;
  }
  var criteria = {token: token}; // 查询条件
  userModel.findOne(criteria, function(error, result){
      if(error) {
          console.log(error);
          callback(201);
      } else {
        if(result){
          var conditions = {id: result.id};
          var update     = {$set : {token : null}};
          userModel.update(conditions, update, function(error){
              if(error) {
                  callback(201);
                  return;
              } else {
                callback(200);
              }
          });
        }else{
            callback(200);
        }
      }
  });
}
UserController.checkToken = function(token, callback){
  if(!token){
    callback(203);
    return;
  }
  var criteria = {token: token}; // 查询条件
  userModel.findOne(criteria, function(error, result){
      if(error) {
          callback(201);
      } else {
        if(result){
          callback(200, {name: result.name, place: result.place});
        }else{
          callback(206)
        }
      }
  });
}

module.exports = UserController; //  与user集合关联
